package com.wuliu.action.sys;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.wuliu.model.common.PageVO;
import com.wuliu.model.common.QueryVO;
import com.wuliu.model.sys.Menu;
import com.wuliu.model.sys.Role;
import com.wuliu.model.sys.User;
import com.wuliu.util.BaseUtil;
import com.wuliu.util.DbUtil;
import com.wuliu.action.BaseAction;
import com.wuliu.business.sys.MenuObj;
import com.wuliu.business.sys.RoleObj;

public class RoleAction extends BaseAction {
	private Role role;
	
    public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public String roleList() {  
		List<QueryVO> list = new ArrayList<QueryVO>(); 
        QueryVO ROLE_ID = new QueryVO("A.ROLE_ID", "选择", "checkbox", "chioce", "");
        list.add(ROLE_ID); 
        
        QueryVO  ROLE_NAME = new QueryVO("A.ROLE_NAME", "角色名称", "1");
        list.add(ROLE_NAME);
        
        QueryVO ROLE_DESC = new QueryVO("A.ROLE_DESC", "角色描述", "1");
        list.add(ROLE_DESC);
        
        QueryVO ACTIVE_FLAG = new QueryVO("(CASE WHEN A.ACTIVE_FLAG='0' THEN '可用' ELSE '不可用' END) AS ACTIVE_FLAG ", "是否可用", "1");
        list.add(ACTIVE_FLAG);
        
        QueryVO ADD_BY = new QueryVO("A.ADD_BY", "创建人", "1");
        list.add(ADD_BY);  
        
        QueryVO ADD_DATE = new QueryVO("A.ADD_DATE", "创建日期", "1");
        list.add(ADD_DATE);
        
        QueryVO ADD_TIME = new QueryVO("A.ADD_TIME", "创建时间", "1");
        list.add(ADD_TIME);
        
        QueryVO UPD_BY = new QueryVO("A.UPD_BY", "最后修改人", "1");
        list.add(UPD_BY);  
        
        QueryVO UPD_DATE = new QueryVO("A.UPD_DATE", "最后修改日期", "1");
        list.add(UPD_DATE);
        
        QueryVO UPD_TIME = new QueryVO("A.UPD_TIME", "最后修改时间", "1");
        list.add(UPD_TIME);
        

        String intStr = "1000";// 需要特殊显示的标记;在原来基础上加1000 
        String tableName = "  WL_ROLE A WHERE 1=1 ";  
 	    
        String orderStr = " ORDER BY A.ROLE_NAME ASC "; 
       
        HashMap<String, String> hm = null; //DBHelper.formQueryToken(request);
        HashMap<String, String> hmSearch = new HashMap<String, String>();
        String searchFlag = BaseUtil.getStr(request.getParameter("searchFlag"));
        String s_role_name = BaseUtil.getStr(request.getParameter("s_role_name"));
        String s_role_desc = BaseUtil.getStr(request.getParameter("s_role_desc"));  
        
    	 if(!s_role_name.equals("")){
           	tableName += " AND A.ROLE_NAME LIKE '%"+s_role_name+"%' "; 
           	hmSearch.put("s_role_name", s_role_name);
         }
    	 if(!s_role_desc.equals("")){
           	tableName += " AND A.ROLE_DESC LIKE '%"+s_role_desc+"%'";
           	hmSearch.put("s_role_desc", s_role_desc);
         } 
    	 
        String pageNum = BaseUtil.getStr(request.getParameter("pageNums"));
        if(pageNum==null||pageNum.equals(""))
            pageNum = "1"; 
        List<?> resultL = DbUtil.queryStrForPage(list, tableName, intStr, hm, orderStr, Integer.parseInt(pageNum));
        int queryCount = DbUtil.queryStrCount(list, tableName, intStr, hm, orderStr);
        PageVO vo = DbUtil.pageObjFor(resultL, pageNum, queryCount);  
        
        request.setAttribute("hmSearch", hmSearch);
        request.setAttribute("searchFlag", searchFlag); 
         
        request.setAttribute("voResult", vo);
        request.setAttribute("qList", list);// 显示名称 
        return "roleList";
	}

    public String saveRole(){
    	if(BaseUtil.getStr(role.getRoleId()).equals("")){
    		String sql	= "INSERT INTO WL_ROLE(ROLE_ID,ROLE_NAME,ROLE_DESC," +
    				" ACTIVE_FLAG,ADD_DATE,ADD_TIME,ADD_BY) " +
    				" VALUES(?,?,?,?,DATE_FORMAT(NOW(),'%Y%m%d') ,DATE_FORMAT(NOW(),'%H%i%s'),?)";
    		List<String> lt = new ArrayList<String>();
    		lt.add(UUID.randomUUID().toString());
    		lt.add(role.getRoleName());
    		lt.add(role.getRoleDesc());
    		lt.add(role.getActiveFlag());
    		lt.add(((User)session.get("user")).getUserName());
    		boolean result	= DbUtil.excuSQL(lt, sql);
    		if(result){
    			request.setAttribute("showMsg","新增成功！");
    		}else{
    			request.setAttribute("showMsg","新增失败！");
    		} 
    	}else{
    		String sql	= "UPDATE WL_ROLE SET ROLE_NAME=?," +
    				"ROLE_DESC=?,ACTIVE_FLAG=?,UPD_DATE=DATE_FORMAT(NOW(),'%Y%m%d')," +
    				"UPD_TIME=DATE_FORMAT(NOW(),'%H%i%s'),UPD_BY=? WHERE ROLE_ID=? ";
    		List<String> lt = new ArrayList<String>();
    		
    		lt.add(role.getRoleName());
    		lt.add(role.getRoleDesc());
    		lt.add(role.getActiveFlag());
    		lt.add(((User)session.get("user")).getUserName());
    		lt.add(role.getRoleId());
    		boolean result	= DbUtil.excuSQL(lt, sql);
    		if(result){
    			request.setAttribute("showMsg","更新成功！");
    		}else{
    			request.setAttribute("showMsg","更新失败！");
    		} 		
    	}
		
    	return roleList();
    }

    public String getRoleInfo(){
    	String id	= BaseUtil.getStr(request.getParameter("id"));
    	Role role = RoleObj.getRoleById(id);

    	JSONObject json = JSONObject.fromObject(role);
    	try {
			response.setCharacterEncoding("utf8");
			response.getWriter().print(json.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
    
	 public String delRole(){
		 String id	= request.getParameter("id");

		 String sql	= "DELETE FROM WL_ROLE WHERE ROLE_ID ='"+id+"'";

		 boolean result	= DbUtil.execute(sql);
		 if(result){
			 request.setAttribute("showMsg","删除成功！");
		 }else{
			 request.setAttribute("showMsg", "删除失败！");
		 }
		 return roleList();
	 }
	 
	 public String getRoleMenu(){
    	String id	= BaseUtil.getStr(request.getParameter("id"));
    	
		List<Menu> menuList = MenuObj.getMenuList();
		List<Menu> roleMenuList = MenuObj.getMenuListByRole(id);
		for(int i=0;i<menuList.size();i++){
			Menu menu = menuList.get(i);
			if(roleMenuList!=null&&roleMenuList.size()>0){
				for(int j=0;j<roleMenuList.size();j++){
					Menu roleMenu = roleMenuList.get(j);
					if(menu.getMenuId().equals(roleMenu.getMenuId())){
						menu.setIsSelect("1");
					}
				}
			}
		}
		
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        Map<String,Object> map = null;
        Menu menu = null;
        for(int i = 0;i < menuList.size();i++){
            menu = menuList.get(i);
            map = new HashMap<String,Object>();
            map.put("id", BaseUtil.getStr(menu.getMenuId()));
            map.put("pId", BaseUtil.getStr(menu.getParentId()));
            map.put("name", BaseUtil.getStr(menu.getMenuName()));
            
            if(menu.getIsSelect() != null && menu.getIsSelect().equals("1")){
                map.put("checked",true);
                map.put("open", true);
            }
            
            result.add(map);
        }

    	JSONArray json = JSONArray.fromObject(result);
    	try {
			response.setCharacterEncoding("utf8");
			response.getWriter().print(json.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
	 
	public String saveRoleMenu(){

		String msg="";
		String roleId = request.getParameter("roleId");
		String menuIds = request.getParameter("menuIds");
		JSONObject json = new JSONObject();
		//先删除绑定的菜单
		String sql = "DELETE FROM WL_ROLE_MENU WHERE ROLE_ID='"+roleId+"' ";
		if(DbUtil.excu(sql)){
			sql = "INSERT INTO WL_ROLE_MENU(RM_ID,ROLE_ID,MENU_ID) " +
					"VALUES(?,?,?) ";
			List<Object[]> par = new ArrayList<Object[]>();
			String[] menuIdArray = menuIds.split(",");
			for(String menuId:menuIdArray){
				Object[] ele = new Object[3];
				ele[0]=UUID.randomUUID().toString();
				ele[1]=roleId;
				ele[2]=menuId;
				par.add(ele);
			}
			if(DbUtil.execute(sql, par)){
				msg="授权成功！";
			}else{
				msg="授权失败！";
			}
		}else{
			msg="授权失败！";
		}
		json.put("msg", msg);
        try {
        	response.setCharacterEncoding("utf8");
            response.getWriter().print(json.toString());
        } catch(Exception ee) {
            System.out.println(ee);
        }
        return null;
	}
}
